// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
     "isLogin":false,
     "userInfo":{}
  },
  
  onLoad: async function(options){
    await this.loginByOpenId();
    this.checkLogin();
  },
  onShow: async function(e) {
    console.log("页面加载事件! e:", e);
  },
  
  loginByOpenId: function() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          console.log(res);
          app.request.post('/app/user/login-by-openid', { js_code: res.code }, (rsp) => {
            console.log('登陆返回:', rsp);
            if(rsp.code===0){
              const data=rsp.data;
              const openId = data.openId;
              console.log('当前用户的OpeId:', openId);
              wx.setStorageSync('openId', openId);
              resolve();
            }
          }, (error) => {
            console.log('登陆异常:', error);
            reject(error);
          })
        }
      })
    });
  },
  checkLogin:function(){
    app.request.post('/app/user/checkLogin', null, (rsp) => {
      console.log('校验登陆返回:', rsp);
      if(rsp.code===0){
        const data=rsp.data;
        if(data!==null && data.userId){
          wx.setStorageSync('userInfo', data);
          this.setData({isLogin:true, userInfo: data});       
        } 
      }    
    },(err)=>{
      wx.showToast({
        title: '网络连接失败',
        icon: 'none',
        duration: 2000
      });
    });
  },
  onLoginTap:function(){
       wx.navigateTo({
         url: '/pages/index/login'
       }) ;
  }
})
